from django.contrib.auth.models import (
    AbstractBaseUser,
    BaseUserManager,
    PermissionsMixin,
)
from django.db import models


class MyUserManager(BaseUserManager):
    def create_user(  # noqa: PLR0913, ANN201
        self, login, mpp, fam, im, ot, password=None
    ):
        """Creates and saves a User with the given login, mpp, fam, im, ot."""  # noqa: D401
        if not login:
            msg = "Вы должны ввести логин"
            raise ValueError(msg)

        user = self.model(
            login=login,
            mpp=mpp,
            fam=fam,
            im=im,
            ot=ot,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(  # noqa: PLR0913, ANN201
        self, login, mpp, fam, im, ot, password=None,
    ):
        """Creates and saves a superuser with the given."""  # noqa: D401
        user = self.create_user(
            login=login, mpp=mpp, fam=fam, im=im, ot=ot, password=password
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser, PermissionsMixin):
    login = models.CharField(max_length=35, unique=True, verbose_name="Логин AD")
    mpp = models.PositiveIntegerField(unique=True,verbose_name="МПП")
    fam = models.CharField(max_length=35, blank=False, verbose_name="Фамилия")
    im = models.CharField(max_length=35, blank=False, verbose_name="Имя")
    ot = models.CharField(max_length=35, default="", verbose_name="Отчество")
    is_active = models.BooleanField(default=True, verbose_name="Активен")
    is_admin = models.BooleanField(default=False, verbose_name="Администратор")

    class Meta:
        verbose_name = "Пользователи"
        verbose_name_plural = "Пользователи"

    objects = MyUserManager()

    USERNAME_FIELD = "login"
    REQUIRED_FIELDS = ("mpp", "fam", "im", "ot")

    def __str__(self) -> str:
        return self.login

    def has_perm(self, perm, obj=None) -> bool:  # noqa: ARG002
        """Does the user have a specific permission?."""  # noqa: D401
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label) -> bool:  # noqa: ARG002
        """Does the user have permissions to view the app."""  # noqa: D401
        # Simplest possible answer: Yes, always
        return True

    def get_full_name(self) -> str:
        return f"{self.fam} {self.im} {self.ot}"

    def get_short_name(self) -> str:
        return f"{self.fam} {self.im[0]}. {self.ot[0]}."

    @property
    def fio(self) -> str:
        return f"{self.fam} {self.im[0]}. {self.ot[0]}."

    @property
    def is_staff(self) -> bool:
        """Is the user a member of staff?."""
        # Simplest possible answer: All admins are staff
        return self.is_admin
